<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="showstu.css">

</head>

<body onload="ajax5()">
<h1 class="title">学生数据展示</h1>
<div id="box">
  <div class="form">

    <form action="" class="update">
      姓名<input type="text" class="xm1" placeholder="请输入更新姓名"><br>
      性别<input type="radio" class="xb1" value="男" name="sex" checked>男
      <input type="radio" value="男" class="xb1" name="sex">女<br>
      年龄<input type="text" placeholder="请输入年龄" class="nl1"><br>
      电话<input type="text" class="dh1"><br>
      成绩<input type="text" class="cj1"><br>
      学校<input type="text" class="xx1"><br>
      <input type="button" id="sub1" value="更新">
    </form>



    <form action="" class="add">
      姓名<input type="text" class="xm" placeholder="请输入姓名"><br>
      性别<input type="radio" class="xb" value="男" name="sex" checked>男
      <input type="radio" value="男" class="xb" name="sex">女<br>
      年龄<input type="text" placeholder="请输入年龄" class="nl"><br>
      电话<input type="text" class="dh"><br>
      成绩<input type="text" class="cj"><br>
      学校<input type="text" class="xx"><br>
      <input type="button" id="sub" value="添加">
    </form>
  </div>
  <div class="show">
    <table class="table">
      <thead>
      <tr class="tr">
        <th class="th">ID</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>电话</th>
        <th>成绩</th>
        <th>学校</th>
        <th>操作1</th>
        <th>操作2</th>
      </tr>
      </thead>
      <tbody id="tab">
      </tbody>
    </table>
  </div>
</div>

</body>

<script>
  let data;
  ajax5();
  function ajax5() {
    //1.创建ajax1对象
    let xmlHttpRequest = new XMLHttpRequest();

    xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax5",true);

    xmlHttpRequest.onreadystatechange=function (){

      if (xmlHttpRequest.readyState == 4){
        if (xmlHttpRequest.status==200){

          data = JSON.parse(xmlHttpRequest.responseText);
          //把json格式的字符串转换成json格式的对象 序列化
          tab.innerHTML = "";
          init();
        }
      }
    }
    xmlHttpRequest.send();
  }
  var pos;
  let tab = document.getElementById("tab");
  var update1 = document.querySelector(".update");
  var add1 = document.querySelector(".add");

  //1.渲染数据
  function init() {
//1.逐条遍历数据
    for (let index = 0; index < data.length;index++) {

//2.生成一行tr
      let tr = document.createElement("tr")

      if (index % 2 == 0) {
        tr.style.backgroundColor = "white";
      }

//3.生成行内的td
      for (let j = 0; j < Object.keys(data[0]).length + 2; j++) {
        let td = document.createElement("td")
        tr.appendChild(td);//添加到tr
      }
//4，给每一行的td赋初值
//       tr.children[0].innerHTML = data[index].id;
//       tr.children[1].innerHTML = data[index].name;
//       tr.children[2].innerHTML = data[index].sex;
//       tr.children[3].innerHTML = data[index].age;
//       tr.children[4].innerHTML = data[index].tel;
//       tr.children[5].innerHTML = data[index].scores;
//       tr.children[6].innerHTML = data[index].school;
       // 想想，上边的代码 3.生成行内的td 能否解耦成下边的简洁代码。
       // 注：data[index]:对象名   Object.keys(data[index])[i]属性名
      //第一种
      // const keysOrder = ['id', 'name', 'sex', 'age', 'tel', 'scores', 'school']; // 定义需要的顺序
      // for (let i = 0; i < keysOrder.length; i++) {
      //   const key = keysOrder[i]; // 获取当前属性名
      //   tr.children[i].innerHTML = data[index][key] !== undefined ? data[index][key] : ''; // 确保值存在
      // }
      //第二种
      for (let i =0;i<Object.keys(data[0]).length;i++) {
        tr.children[i].innerHTML=data[index][Object.keys(data[index])[i]];
      }

//5.创建操作按钮
      let button = document.createElement("button")
      let button1 = document.createElement("button")
      button.innerHTML = "删除";
      button1.innerHTML = "更新";
//2.删除数据
      button.onclick = del(index);
      button1.onclick =update(index);
//6.添加按钮对象
      tr.children[Object.keys(data[0]).length].appendChild(button)
      tr.children[Object.keys(data[0]).length+1].appendChild(button1)

      tab.appendChild(tr);
    }
  }

  //点击按钮实现，删除操作
  function del(index) {//想想，为啥这么写？好处是啥
    return function () {

      if (window.confirm("你确定要删除吗？")) {
        let sc={
          id:data[index].id
        }
        //字符串  对象--》后端  --》对象  序列化
        let s = encodeURIComponent(JSON.stringify(sc));
        //1.创建ajax1对象
        let xmlHttpRequest = new XMLHttpRequest();
//2.配置向后端请求类型get post 异步请求数据 传递数据 2 &
        xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax7?id="+s,true);
//监听数据是否请求成功
        xmlHttpRequest.onreadystatechange=function (){
//服务和客户端握手
          if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status==200){
            if (xmlHttpRequest.responseText=="success"){
              alert("数据删除成功");
              tab.innerHTML = "";
              add1.reset();
              ajax5();
            }
          }
        }
        //4.发送请求
        xmlHttpRequest.send();
        // data.splice(index, 1);
        // tab.innerHTML = "";
        // init();
      }
    }

  }

  //点击按钮，实现数据回显效果
  function update(index){//想想，为啥这么写？好处是啥
    return function () {
      var update = document.querySelector(".update");
      var add = document.querySelector(".add");
// update.style.display = "none";
// add.style.display = "block";
// data[data.length-1].id+1;
      document.querySelector(".xm1").value = data[index].name
// document.querySelectorAll(".xb1")[0].checked?"男":"女";
      document.querySelector(".nl1").value = data[index].age;
      document.querySelector(".dh1").value = data[index].tel;
      document.querySelector(".cj1").value = data[index].scores
      document.querySelector(".xx1").value = data[index].school
      pos=index;//记录更新的数组下标
    }

  }


  //3.数据添加
  let sub = document.getElementById("sub")
  sub.onclick = function () {
    let id = data[data.length - 1].id + 1;
    let xm = document.querySelector(".xm").value
    let xb = document.querySelectorAll(".xb")[0].checked ? "男" : "女";
    let nl = document.querySelector(".nl").value
    let dh = document.querySelector(".dh").value
    let cj = document.querySelector(".cj").value
    let xx = document.querySelector(".xx").value
//数据入库
    let newobj = {
      "id": id,
      "name": xm,
      "sex": xb,
      "age": nl,
      "tel": dh,
      "scores": cj,
      "school": xx
    }

    //字符串  对象--》后端  --》对象  序列化
    let s = encodeURIComponent(JSON.stringify(newobj));
    //1.创建ajax1对象
    let xmlHttpRequest = new XMLHttpRequest();
//2.配置向后端请求类型get post 异步请求数据 传递数据 2 &
    xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax6?data="+s,true);
//监听数据是否请求成功
    xmlHttpRequest.onreadystatechange=function (){
//服务和客户端握手
      if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status==200){
        if (xmlHttpRequest.responseText=="success"){
          alert("数据入库成功");
          tab.innerHTML = "";
          add1.reset();
          ajax5();
        }
      }
    }
    //4.发送请求
    xmlHttpRequest.send();
    // data.push(newobj);//数据添加仓库之后，重新渲染界面

    // init();//调用init方法重新渲染界面
  }

  //4实现更新
  let sub1 = document.getElementById("sub1")
  sub1.onclick = function () {
    let id = data[pos].id;
    let xm = document.querySelector(".xm1").value
    let xb = document.querySelectorAll(".xb1")[0].checked ? "男" : "女";
    let nl = document.querySelector(".nl1").value
    let dh = document.querySelector(".dh1").value
    let cj = document.querySelector(".cj1").value
    let xx = document.querySelector(".xx1").value
//更新这条数据
    let pos1 = {
      "id": id,
      "name": xm,
      "sex": xb,
      "age": nl,
      "tel": dh,
      "scores": cj,
      "school": xx
    }
    //字符串  对象--》后端  --》对象  序列化
    let update = encodeURIComponent(JSON.stringify(pos1));
    //1.创建ajax1对象
    let xmlHttpRequest = new XMLHttpRequest();
//2.配置向后端请求类型get post 异步请求数据 传递数据 2 &
    xmlHttpRequest.open("get","/servletstudy_war_exploded/ajax8?upd="+update,true);
//监听数据是否请求成功
    xmlHttpRequest.onreadystatechange=function (){
//服务和客户端握手
      if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status==200){
        if (xmlHttpRequest.responseText=="success"){
          alert("数据更新成功");
          tab.innerHTML = "";
          update1.reset();
          ajax5();
        }
      }
    }
    //4.发送请求
    xmlHttpRequest.send();

    // tab.innerHTML = "";
    // init();//调用init方法重新渲染界面
  }
</script>

</html>